package com.txzt.gaea.upgrade.project.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.fastjson.JSONArray;
import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.aspect.annotation.SysDataPermission;
import com.txzt.gaea.base.service.DictInfoService;
import com.txzt.gaea.business.util.TranslateUtil;
import com.txzt.gaea.common.annotation.EntityCommonValue;
import com.txzt.gaea.common.base.controller.BaseController;
import com.txzt.gaea.common.enums.IsDeleteEnum;
import com.txzt.gaea.upgrade.project.domain.model.BudgetManage;
import com.txzt.gaea.upgrade.project.domain.model.SubItem;
import com.txzt.gaea.upgrade.project.service.IBudgetManageService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/budget/manage")
public class BudgetManageController extends BaseController {

    @Autowired
    private IBudgetManageService budgetManageService;
    @Autowired
    private DictInfoService dictInfoService;


    /**
     * 分页查询
     *
     * @param budgetManage
     * @return
     */
    @SysDataPermission
    @GetMapping(value = "/list")
    public RtnInfo<?> pageList(@RequestParam(defaultValue = "1") Integer pageNumber,
                                      @RequestParam(defaultValue = "10") Integer pageSize, BudgetManage budgetManage) {
        PageQuery<BudgetManage> pageList = budgetManageService.pageQuery(new PageQuery<>(pageNumber, pageSize, budgetManage));
        pageList.getList().forEach(item ->{
            //翻译提报人
            item.setCreateByName(TranslateUtil.getUserName(item.getCreateBy()));
            //翻译提报部门
            item.setDeptName(TranslateUtil.getDepartmentName(item.getDeptId()));
        });
        return RtnInfo.success(pageList);
    }

    /**
     * 查询待审核数量(经费预算)
     * @param budgetManage
     * @return
     */
    @SysDataPermission
    @GetMapping(value = "/listCheckCount")
    public RtnInfo<?> listCheckCount(BudgetManage budgetManage) {
        Long count = budgetManageService.listCheckCount(budgetManage);
        return RtnInfo.success(count);
    }

    /**
     * 新增
     * @param budgetManage
     * @return
     */
    @PostMapping(value = "/add")
    @EntityCommonValue(operation = "CREATE")
    public RtnInfo<?> add(@RequestBody BudgetManage budgetManage) {
        int count = budgetManageService.addBudgetManage(budgetManage);
        if (count > 0) {
            return RtnInfo.SUCCESS;
        } else {
            return RtnInfo.SERVER_ERROR;
        }
    }

    /**
     * 更新
     * @param budgetManage
     * @return
     */
    @PutMapping(value = "/edit")
    @EntityCommonValue(operation = "UPDATE")
    public RtnInfo<?> edit(@RequestBody BudgetManage budgetManage) {
        int count = budgetManageService.editBudgetManage(budgetManage);
        if (count > 0) {
            return RtnInfo.SUCCESS;
        } else {
            return RtnInfo.SERVER_ERROR;
        }
    }

    /**
     * 撤回
     * @param budgetManage
     * @return
     */
    @PutMapping(value = "/revocation")
    @EntityCommonValue(operation = "UPDATE")
    public RtnInfo<?> revocation(@RequestBody BudgetManage budgetManage) {
        int count = budgetManageService.revocationBudgetManage(budgetManage);
        if (count > 0) {
            return RtnInfo.SUCCESS;
        } else {
            return RtnInfo.SERVER_ERROR;
        }
    }



    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    @EntityCommonValue(operation = "UPDATE")
    public RtnInfo<?> delete(@RequestParam Long id) {
        BudgetManage budgetManage = new BudgetManage();
        budgetManage.setId(id);
        budgetManage.setIsDelete(IsDeleteEnum.DELETE.getCode());
        int count = budgetManageService.updateById(budgetManage);
        if (count > 0) {
            return RtnInfo.SUCCESS;
        } else {
            return RtnInfo.SERVER_ERROR;
        }
    }

    /**
     * 导出
     */
    @GetMapping(value = "/export")
    public void exportExcel(HttpServletResponse response, @RequestParam(defaultValue = "1") Integer pageNumber,
                            @RequestParam(defaultValue = "10") Integer pageSize, BudgetManage budgetManage) throws IOException {
        PageQuery<BudgetManage> pageList = budgetManageService.pageQuery(new PageQuery<>(pageNumber, pageSize, budgetManage));
        pageList.getList().forEach(item -> {
            //翻译部门
            item.setDeptName(TranslateUtil.getDepartmentName(item.getDeptId()));
            //预算科目翻译
            item.setLedgerAccountName(dictInfoService.dictTranslate("ledger_account",item.getLedgerAccount()));
        });
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("项目经费预算管理", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), BudgetManage.class)
                .sheet("数据列表")
                .doWrite(pageList.getList());
    }

    @Value("${template.budgetTemplate}")
    String budgetTemplate;

    /**
     * 经费预算申请信息导出（方案一）
     * @param ids
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/exportBudget")
    public void exportExcelTest1(Long[] ids ,HttpServletResponse response) throws IOException {
        List<BudgetManage> manageList = budgetManageService.selectByIds(ids);
        List<SubItem> itemList = new ArrayList<>();
        for (BudgetManage manage : manageList){
            itemList.add(new SubItem(null,
                    dictInfoService.dictTranslate("capacity_building",manage.getCapacityBuildingOne()),
                    dictInfoService.dictTranslate("ledger_account",manage.getLedgerAccount())
            ));
            itemList.add(new SubItem(manage.getBudgetName(),null,null));
            itemList.addAll(JSONArray.parseArray(manage.getSubItem(),SubItem.class));
        }
        BigDecimal sum = BigDecimal.ONE;
        for (SubItem item : itemList){
            sum = sum.add(null == item.getAmount() ? BigDecimal.ONE : item.getAmount());
        }
        itemList.add(0,new SubItem(sum));
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(budgetTemplate).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
                excelWriter.fill(new FillWrapper(itemList), writeSheet);
        }
    }

    /**
     * 经费预算申请信息导出（方案二）
     * @param ids
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/exportTest")
    public void exportExcelTest2(Long[] ids,HttpServletResponse response) throws IOException {
        List<BudgetManage> manageList = new ArrayList<>();
        for (Long id: ids){
            BudgetManage budgetManage = budgetManageService.selectById(id);
            manageList.add(budgetManage);
        }
        Workbook workbook = new XSSFWorkbook(budgetTemplate);
        Sheet sheet = workbook.getSheetAt(0);
        int rowIndex = 4;
        for (BudgetManage budgetManage : manageList){
            Row row1 = sheet.getRow(rowIndex);
            row1.getCell(1).setCellValue(dictInfoService.dictTranslate("capacity_building",budgetManage.getCapacityBuildingOne()));
            row1.getCell(2).setCellValue(dictInfoService.dictTranslate("ledger_account",budgetManage.getLedgerAccount()));
            Row row2 = sheet.getRow(++rowIndex);
            row2.getCell(3).setCellValue(budgetManage.getBudgetName());
            List<SubItem> itemList = JSONArray.parseArray(budgetManage.getSubItem(),SubItem.class);
            for (SubItem item : itemList){
                Row row3 = sheet.getRow(++rowIndex);
                row3.getCell(3).setCellValue(item.getTwoSubitem());
                row3.getCell(4).setCellValue(item.getThreeSubitem());
                row3.getCell(5).setCellValue(item.getCompany());
                row3.getCell(6).setCellValue(item.getQuantity());
                row3.getCell(7).setCellValue(item.getUnitPrice());
                row3.getCell(8).setCellValue(item.getAmount().doubleValue());
                row3.getCell(9).setCellValue(item.getAchievements());
                row3.getCell(10).setCellValue(item.getRemarks());
            }

        }
        workbook.write(response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }



}
